//
// Created by LiuYou on 2021/8/20.
//

#include <exception>
#include "Condition.hpp"

Condition::Condition() {
    if (pthread_mutex_init( &mutex, nullptr ) != 0) {
        throw std::exception();
    }
    if (pthread_cond_init( &condition, nullptr ) != 0) {
        pthread_mutex_destroy( &mutex );
        throw std::exception();
    }
}

Condition::~Condition() {
    pthread_mutex_destroy( &mutex );
    pthread_cond_destroy( &condition );
}

bool Condition::wait() {
    pthread_mutex_lock( &mutex );
    int ret = pthread_cond_wait( &condition, &mutex );
    pthread_mutex_unlock( &mutex );
    return ret == 0;
}

bool Condition::signal() {
    return pthread_cond_signal( &condition ) == 0;
}
